<template>
  <el-dialog
    v-model="visible"
    title="选择评估岗位"
    width="600px"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
  >
    <div class="job-selection-content">
      <div class="description">
        <el-alert
          title="AI评估说明"
          type="info"
          :closable="false"
          show-icon
        >
          <template #default>
            <p>AI将根据您选择的目标岗位要求，对您的简历进行专业评估，包括：</p>
            <ul>
              <li>简历与岗位的匹配度分析</li>
              <li>简历优势和亮点总结</li>
              <li>改进建议和优化方向</li>
              <li>求职准备和面试建议</li>
            </ul>
          </template>
        </el-alert>
      </div>

      <div class="job-search">
        <el-form :model="searchForm" inline>
          <el-form-item label="搜索岗位">
            <el-input
              v-model="searchForm.keyword"
              placeholder="输入岗位名称或公司名称"
              style="width: 300px"
              @input="handleSearch"
              clearable
            >
              <template #prefix>
                <el-icon><Search /></el-icon>
              </template>
            </el-input>
          </el-form-item>
        </el-form>
      </div>

      <div class="job-list" v-loading="loading">
        <div v-if="jobList.length === 0" class="empty-state">
          <el-empty description="暂无可选择的岗位">
            <el-button type="primary" @click="handleRefresh">
              刷新岗位列表
            </el-button>
          </el-empty>
        </div>

        <div v-else class="job-grid">
          <el-card
            v-for="job in jobList"
            :key="job.id"
            class="job-card"
            shadow="hover"
            :class="{ 'selected': selectedJobId === job.id }"
            @click="handleJobSelect(job)"
          >
            <div class="job-header">
              <div class="job-title">{{ job.title }}</div>
              <div class="company-name">{{ job.company_name }}</div>
            </div>
            <div class="job-info">
              <div class="info-item">
                <span class="label">工作地点：</span>
                <span class="value">{{ job.work_location }}</span>
              </div>
              <div class="info-item">
                <span class="label">学历要求：</span>
                <span class="value">{{ job.education_requirement || '不限' }}</span>
              </div>
              <div class="info-item">
                <span class="label">经验要求：</span>
                <span class="value">{{ job.experience_requirement || '不限' }}</span>
              </div>
            </div>
            <div class="job-description">
              {{ job.description || '暂无描述' }}
            </div>
          </el-card>
        </div>

        <!-- 分页 -->
        <div class="pagination-wrapper" v-if="pagination.total > 0">
          <el-pagination
            v-model:current-page="pagination.page"
            v-model:page-size="pagination.pageSize"
            :page-sizes="[6, 12, 18]"
            :total="pagination.total"
            layout="total, sizes, prev, pager, next"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            small
          />
        </div>
      </div>
    </div>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleCancel">取消</el-button>
        <el-button
          type="primary"
          @click="handleConfirm"
          :disabled="!selectedJobId"
        >
          开始AI评估
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive, watch, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { Search } from '@element-plus/icons-vue'
import { jobApi, type Job } from '@/api/jobs'
import type { Resume } from '@/api/resume'

interface Props {
  modelValue: boolean
  resume: Resume | null
}

interface Emits {
  (e: 'update:modelValue', value: boolean): void
  (e: 'confirm', jobId: number): void
}

const props = defineProps<Props>()
const emit = defineEmits<Emits>()

// 响应式数据
const visible = ref(false)
const loading = ref(false)
const jobList = ref<Job[]>([])
const selectedJobId = ref<number | null>(null)

// 搜索表单
const searchForm = reactive({
  keyword: ''
})

// 分页数据
const pagination = reactive({
  page: 1,
  pageSize: 6,
  total: 0
})

// 监听 modelValue 变化
watch(() => props.modelValue, (newValue) => {
  visible.value = newValue
  if (newValue) {
    // 对话框打开时重置状态并加载岗位列表
    selectedJobId.value = null
    searchForm.keyword = ''
    pagination.page = 1
    fetchJobList()
  }
})

// 监听 visible 变化
watch(visible, (newValue) => {
  emit('update:modelValue', newValue)
})

// 获取岗位列表
const fetchJobList = async () => {
  loading.value = true
  try {
    const params = {
      page: pagination.page,
      page_size: pagination.pageSize,
      status: 'published', // 只获取已发布的岗位
      ...(searchForm.keyword && { search: searchForm.keyword })
    }

    const response = await jobApi.getJobList(params)
    const data = response.data || response
    jobList.value = data.results || []
    pagination.total = data.count || 0
  } catch (error) {
    console.error('获取岗位列表失败:', error)
    ElMessage.error('获取岗位列表失败')
  } finally {
    loading.value = false
  }
}

// 处理搜索
const handleSearch = () => {
  pagination.page = 1
  fetchJobList()
}

// 处理刷新
const handleRefresh = () => {
  searchForm.keyword = ''
  pagination.page = 1
  fetchJobList()
}

// 处理分页大小变化
const handleSizeChange = (size: number) => {
  pagination.pageSize = size
  pagination.page = 1
  fetchJobList()
}

// 处理页码变化
const handleCurrentChange = (page: number) => {
  pagination.page = page
  fetchJobList()
}

// 处理岗位选择
const handleJobSelect = (job: Job) => {
  selectedJobId.value = job.id
}

// 处理确认
const handleConfirm = () => {
  if (!selectedJobId.value) {
    ElMessage.warning('请选择一个岗位')
    return
  }
  emit('confirm', selectedJobId.value)
  visible.value = false
}

// 处理取消
const handleCancel = () => {
  visible.value = false
}
</script>

<style lang="scss" scoped>
.job-selection-content {
  .description {
    margin-bottom: 20px;

    :deep(.el-alert__content) {
      p {
        margin: 0 0 8px 0;
        line-height: 1.5;
      }

      ul {
        margin: 8px 0 0 0;
        padding-left: 20px;

        li {
          margin-bottom: 4px;
          line-height: 1.4;
        }
      }
    }
  }

  .job-search {
    margin-bottom: 20px;
    padding: 16px;
    background: var(--fill-color-extra-light);
    border-radius: 6px;
  }

  .job-list {
    .empty-state {
      padding: 40px 0;
      text-align: center;
    }

    .job-grid {
      display: grid;
      grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
      gap: 16px;
      margin-bottom: 20px;

      .job-card {
        cursor: pointer;
        transition: all 0.3s ease;
        border: 2px solid transparent;

        &:hover {
          transform: translateY(-2px);
          box-shadow: 0 4px 16px rgba(0, 0, 0, 0.1);
        }

        &.selected {
          border-color: var(--color-primary);
          box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.2);
        }

        .job-header {
          margin-bottom: 12px;

          .job-title {
            font-size: 16px;
            font-weight: 600;
            color: var(--text-color-primary);
            margin-bottom: 4px;
          }

          .company-name {
            font-size: 14px;
            color: var(--text-color-secondary);
          }
        }

        .job-info {
          margin-bottom: 12px;

          .info-item {
            display: flex;
            margin-bottom: 4px;
            font-size: 13px;

            .label {
              color: var(--text-color-secondary);
              min-width: 70px;
            }

            .value {
              color: var(--text-color-primary);
              flex: 1;
            }
          }
        }

        .job-description {
          font-size: 13px;
          color: var(--text-color-regular);
          line-height: 1.4;
          display: -webkit-box;
          -webkit-line-clamp: 2;
          -webkit-box-orient: vertical;
          overflow: hidden;
        }
      }
    }

    .pagination-wrapper {
      display: flex;
      justify-content: center;
      margin-top: 20px;
    }
  }
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

@media (max-width: 768px) {
  .job-selection-content {
    .job-list {
      .job-grid {
        grid-template-columns: 1fr;
      }
    }
  }
}
</style>
